package com.sugon.modules.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.sugon.dao.DeviceInfoDao;
import com.sugon.entity.SysDeptEntity;
import com.sugon.modules.sys.model.vo.DeviceOrganizationVO;
import com.sugon.modules.sys.service.ISysDeptManager;
import com.sugon.modules.sys.utils.TreeNodeUtils;
import com.sugon.service.SysConfigService;
import com.sugon.service.SysDeptService;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ： YuXD
 * @description： 系统组织结构Manager实现类
 * @date ： 2020-11-14 下午 6:34
 * @version: 1.0
 */
@Service
public class SysDeptManagerImpl implements ISysDeptManager {

    @Autowired
    private SysDeptService deptService;
    @Autowired
    private DeviceInfoDao deviceInfoDao;
    @Autowired
    private SysConfigService configService;

    @Override
    public List<DeviceOrganizationVO> loadDeviceOrganization(Integer deptLevel) {
        // 默认查看全部的
        if (deptLevel == null) {
            deptLevel = 3;
        }
        List<SysDeptEntity> devOrgDeptList = deptService.treeDeptByLevel(deptLevel);
        // 找出设备组织
        List<DeviceOrganizationVO> deviceOrganizationList = CollectionUtil.newArrayList();
        // 整合数据到一起
        for (SysDeptEntity devOrgDept : devOrgDeptList) {
            deviceOrganizationList.add(new DeviceOrganizationVO(devOrgDept));
        }
        // 构建设备组织树
        TreeNodeUtils treeNodeUtils = new TreeNodeUtils(deviceOrganizationList);
        DeviceOrganizationVO root = treeNodeUtils.generateTree("01");
        return root.getChildren();
    }

    @Override
    public Integer getWorkshopTriggerTime(String lineCode) {
        Integer workshopTriggerTime = null;
        SysDeptEntity dept = deptService.getByDCode(lineCode);
        Assert.notNull(dept, "产线[" + lineCode + "]设备组织不存在！");
        workshopTriggerTime = dept.getWorkshopTriggerTime();
        if (workshopTriggerTime == null) {
            workshopTriggerTime = configService.getWorkshopTriggerTime();
            dept.setWorkshopTriggerTime(workshopTriggerTime);
            deptService.update(dept);
        }
        return workshopTriggerTime;
    }

    @Override
    public Integer getFactoryTriggerTime(String lineCode) {
        Integer factoryTriggerTime = null;
        SysDeptEntity dept = deptService.getByDCode(lineCode);
        Assert.notNull(dept, "产线[" + lineCode + "]设备组织不存在！");
        factoryTriggerTime = dept.getFactoryTriggerTime();
        if (factoryTriggerTime == null) {
            factoryTriggerTime = configService.getFactoryTriggerTime();
            dept.setFactoryTriggerTime(factoryTriggerTime);
            deptService.update(dept);
        }
        return factoryTriggerTime;
    }
}
